﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OSGeo.MapGuide;
using System.Xml;
using System.Text;
using System.Configuration;
using System.Collections.Specialized;


namespace NegevGas.Extensions.SearchInBlock
{
    //    public partial class _default : System.Web.UI.Page
    //    {
    //        protected void Page_Load(object sender, EventArgs e)
    //        {

    //        }
    //    }
    //}



    public partial class _default : utilityfunctions
    {
        private bool __debugMode = bool.Parse(ConfigurationManager.AppSettings["DEBUG_MODE"]);

        private const string KeySession = "SESSION";
        private const string KeyMapName = "MAPNAME";
        private const string KeyLayer = "LAYER";
        private const string KeyFilter = "FILTER";
        private const string KeyMatchLimit = "MR";
        private const string KeyProperty = "Property";
        private const string KeyFilterOperation = "FILTER_OPERATOP";
        private const string KeyACLayer = "ACLayer";
        private const string KeyACProperty = "ACProperty";
        private const string KeyIsString = "IsString";
        private const string KeyDistinct = "DISTINCT";
        private const string NullFiled="NullFiled";
        
        private MgSiteConnection conn;
        private MgFeatureService featureService;
        private MgResourceService resourceService;
        private MgMap map;
        private MgLayer layer;
        private string sessionId = string.Empty;
        private utilityfunctions utils = new utilityfunctions();

        private bool _whithError = false;

        public  int matchLimit = 0;
        public int numCols = 0;
        public string locale = string.Empty;
        public string layerId = string.Empty;
        public string mapName = string.Empty;
        public string filter = string.Empty;
        public string acProperty = string.Empty;
        public string acLayer = string.Empty;
        public string property = string.Empty;
        public string NullFiledVal = string.Empty;
        public Dictionary<string, string> displayProperties;

        private bool distinct = false;
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            txtSearch.Multiple = true;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Common variables
                sessionId = Request[KeySession];
                Session[KeySession] = sessionId;
                ViewState.Add(KeySession, sessionId);

                mapName = Request[KeyMapName];
                Session[KeyMapName] = mapName;
                ViewState.Add(KeyMapName, mapName);

                //Variables for autocomplete
                acLayer = Request[KeyACLayer] ?? Request[KeyLayer];


              
                Session[KeyACLayer] = acLayer;

                NullFiledVal = Request[NullFiled];
            
                ViewState.Add(NullFiled, NullFiledVal);
                Session[NullFiled] = NullFiledVal;

                acProperty = Request[KeyACProperty] ?? Request[KeyProperty];
                Session[KeyACProperty] = acProperty;

                bool isString = checkProperty(acProperty);
                Session[KeyIsString] = isString;

                //Variables for search
                layerId = Request[KeyLayer];
                ViewState.Add(KeyLayer, layerId);
                foreach (string item in GetAllCompletionList("null", 10, "null"))
                {
                    ListItem tete = new ListItem();
                    tete.Text = item;
                    tete.Value = item;
                    txtSearch.Items.Add(tete);
                }
                
                int ix = 0;
                displayProperties = new Dictionary<string, string>();
                if (Request["PROPDISPLAY-CAP"] != null && Request["PROPDISPLAY-VAL"] != null)
                {
                    displayProperties.Add(Request["PROPDISPLAY-VAL"], Request["PROPDISPLAY-CAP"]);
                }
                while (Request[String.Format("CP{0}", ix)] != null || Request[String.Format("CN{0}", ix)] != null)
                {
                    displayProperties.Add(Request[String.Format("CP{0}", ix)], Request[String.Format("CN{0}", ix)]);
                    ix++;
                }
                ViewState.Add("DisplayProperties", displayProperties);

                property = Request[KeyProperty];
                string op = Request[KeyFilterOperation].Replace("EQUAL", "=");
                string filterFormat = String.Empty;

                if (op.ToUpper() == "LIKE")
                {
                    filterFormat = "\"{0}\" {1} '%$USER_VARIABLE%'";
                }
                else
                {
                    filterFormat = checkProperty(property, layerId) ? "\"{0}\" {1} '$USER_VARIABLE'" : "\"{0}\" {1} $USER_VARIABLE";
                }
                filter = String.Format(filterFormat, property, op);
                ViewState.Add(KeyFilter, filter);

                if (!string.IsNullOrEmpty(Request[KeyDistinct]))
                {
                    if (Request[KeyDistinct].ToUpper() == "YES" || Request[KeyDistinct].ToUpper() == "TRUE" || Request[KeyDistinct].ToUpper() == "1")
                        distinct = true;
                }
                ViewState[KeyDistinct] = distinct;

                if (!int.TryParse(Request[KeyMatchLimit], out matchLimit))
                    matchLimit = 0;
                ViewState.Add(KeyMatchLimit, matchLimit);
            }
            else
            {
                sessionId = ViewState[KeySession].ToString();
                mapName = ViewState[KeyMapName].ToString();
                layerId = ViewState[KeyLayer].ToString();
                filter = ViewState[KeyFilter].ToString();
                matchLimit = (int)ViewState[KeyMatchLimit];
                NullFiledVal = ViewState[NullFiled].ToString();
            }

          //  string[] allcountries = 
               

            if (!_whithError)
            {
                _ErrorMessage.Visible = false;
            }
            _whithError = false;
        }

        protected void Search(object sender, EventArgs e)
        {
            if (filter == string.Empty) return;

            filter = filter.Replace("$USER_VARIABLE", txtSearch.Value);

            numCols = 1;

            Dictionary<string, string> displayColumns = new Dictionary<string, string>();
            displayColumns = ViewState["DisplayProperties"] as Dictionary<string, string>;//.Add(Request["CP0"], Request["CN0"]);

            try
            {
                utils.InitializeWebTier();
                conn = new MgSiteConnection();
                conn.Open(new MgUserInformation(sessionId));
                resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService;
                featureService = conn.CreateService(MgServiceType.FeatureService) as MgFeatureService;
                map = new MgMap();
                map.Open(resourceService, mapName);
                layer = map.GetLayers().GetItem(layerId) as MgLayer;
                if (layer == null)
                {
                    throw new doSearchException("שכבה לא קיימת.");
                }
                string acFilter = checkProperty(Session[KeyACProperty].ToString(), Session[KeyACLayer].ToString()) ? String.Format("{0}='{1}'", Session[KeyACProperty].ToString(), txtSearch.Value) : String.Format("{0}={1}", Session[KeyACProperty].ToString(), txtSearch.Value);
                string mainSelection = GetMainFeatureSelection(Session[KeyACLayer].ToString(), acFilter);

                litResultPanelTitle.Text = String.Format("<div class='searchResultTitle' onclick=\"parent.parent.mapFrame.SetSelectionXML('{1}');parent.parent.mapFrame.ZoomSelection();\">{0}</div>", txtSearch.Value, Server.HtmlEncode(mainSelection));

                MgFeatureQueryOptions opt = new MgFeatureQueryOptions();
                opt.SetFilter(filter);
                StringBuilder resultHtml = new StringBuilder();
                resultHtml.AppendLine("<table id='resultTable' class='sort' cellspacing='0' cellpadding='0' width='100%'>");
                resultHtml.AppendLine("<thead><tr style='display:none'>");

                foreach (var item in displayColumns)
                {
                    resultHtml.AppendFormat("<td>{0}</td>", item.Value);
                }

                resultHtml.AppendLine("</tr></thead>");

                MgFeatureReader reader = featureService.SelectFeatures(
                                            new MgResourceIdentifier(layer.FeatureSourceId),
                                            layer.FeatureClassName,
                                            opt
                                         );

                resultHtml.Append(GetValuesTable(reader, displayColumns));
                resultHtml.AppendLine("</table>");
                ResultPanel.Visible = true;
                ResultContainer.Text = resultHtml.ToString();
            }
            catch (doSearchException ex)
            {
                _whithError = true;
                ShowError(ex.Message);
            }
            catch (MgException ex)
            {
                _whithError = true;
                if (__debugMode)
                    ShowError(ex.Message);
                else
                    ShowError("שגיאה, אנא וודא תקינות שאילתא.");
            }
        }
        private void GetPropertiesFields(Dictionary<string, string> columnCollection)
        {
            MgByteReader reader = resourceService.GetResourceContent(layer.LayerDefinition);
            string xmlSchema = reader.ToString();
            reader.Dispose();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlSchema);
            XmlNodeList xmlProperties = xmlDoc.GetElementsByTagName("PropertyMapping");
            foreach (XmlNode node in xmlProperties)
            {
                string Name = node.SelectSingleNode("Name").InnerText;
                string Alias = node.SelectSingleNode("Value").InnerText;
                columnCollection.Add(Name, Alias);
            }
        }
        private string[] GetPrimaryKeyFieldName()
        {
            string schemaName = layer.FeatureClassName.Split(':')[0];
            MgFeatureSchemaCollection schema = featureService.DescribeSchema(new MgResourceIdentifier(layer.FeatureSourceId), schemaName);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(featureService.SchemaToXml(schema));

            XmlNamespaceManager nsmr = new XmlNamespaceManager(doc.NameTable);
            nsmr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            XmlNodeList elements = doc.GetElementsByTagName("xs:key");
           // XmlNodeList nodes = elements[0].SelectNodes("xs:field", nsmr);
             XmlNodeList nodes = elements[0].SelectNodes("xs:field", nsmr);
           
            List<string> keys = new List<string>();
            foreach (XmlNode node in nodes)
            {
                keys.Add(node.Attributes["xpath"].Value);
            }
            return keys.ToArray();
        }
        private string GetValuesTable(MgFeatureReader reader, Dictionary<string, string> columnsCollection)
        {
            string[] keyFields = GetPrimaryKeyFieldName();
            List<string> ids = new List<string>();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<tbody>");
            bool alternate = true;
            int row = 0;
            bool hasResults = false;
            List<string> results = new List<string>();

            while (reader.ReadNext())
            {
                hasResults = true;
                bool isEmptyRow = true;
                StringBuilder sb1 = new StringBuilder();
                sb1.AppendLine(string.Format("<tr class='resultRow{0}'>", alternate ? "0" : "1"));
                alternate = !alternate;
                int column = 0;
                foreach (var item in columnsCollection)
                {
                    string val = string.Empty;
                    try
                    {
                        val = GetPropertyValue(reader, item.Key);

                        if (((bool)ViewState[KeyDistinct]) && results.Contains(val)) continue;
                        results.Add(val);
                        if (!string.IsNullOrEmpty(val))
                        {
                            sb1.AppendFormat("<td id='{1}:{2}' onclick=\"CellClicked('{3}')\">{0}</td>", val, row, column++, GetSelectionXml(reader, keyFields));
                            isEmptyRow = false;
                        }
                    }
                    catch { throw; }
                }
                sb1.AppendLine("</tr>");
                if (!isEmptyRow) sb.Append(sb1.ToString());
                if (++row == matchLimit) break;
            }
            sb.AppendLine("</tbody>");
            if (!hasResults) throw new doSearchException("אין תוצאות");
            return sb.ToString();
        }
        private string GetSelectionXml(MgFeatureReader reader, string[] keys)
        {
            MgSelection sel = new MgSelection(map);
            MgPropertyCollection idProps = new MgPropertyCollection();

            for (int i = 0; i < keys.Length; i++)
            {
                int idPropType = reader.GetPropertyType(keys[i]);
                switch (idPropType)
                {
                    case MgPropertyType.Int32:
                        idProps.Add(new MgInt32Property(keys[i], reader.GetInt32(keys[i])));
                        break;
                    case MgPropertyType.String:
                        idProps.Add(new MgStringProperty(keys[i], reader.GetString(keys[i])));
                        break;
                    case MgPropertyType.Int64:
                        idProps.Add(new MgInt64Property(keys[i], reader.GetInt64(keys[i])));
                        break;
                    case MgPropertyType.Double:
                        idProps.Add(new MgDoubleProperty(keys[i], reader.GetDouble(keys[i])));
                        break;
                    case MgPropertyType.Single:
                        idProps.Add(new MgSingleProperty(keys[i], reader.GetSingle(keys[i])));
                        break;
                    case MgPropertyType.DateTime:
                        idProps.Add(new MgDateTimeProperty(keys[i], reader.GetDateTime(keys[i])));
                        break;
                    default:
                        break;
                }
            }
            sel.AddFeatureIds(layer, layer.FeatureClassName, idProps);

            return HttpUtility.HtmlEncode(sel.ToXml());
        }
        private void ShowError(string message)
        {
            _whithError = true;
            _ErrorMessage.Visible = true;
            _ErrorMessage.Controls.Clear();
            _ErrorMessage.Controls.Add(new Label() { Text = message, CssClass = "doErrorMessage" });
            ResultPanel.Visible = false;
        }

       
        public void SearchMulti(object sender, EventArgs e)
        {
            if (filter == string.Empty) return;

            filter = filter.Replace("$USER_VARIABLE", txtSearch.Value);

            numCols = 1;

            Dictionary<string, string> displayColumns = new Dictionary<string, string>();
            displayColumns = ViewState["DisplayProperties"] as Dictionary<string, string>;//.Add(Request["CP0"], Request["CN0"]);

             try
            {
                utils.InitializeWebTier();
                conn = new MgSiteConnection();
                conn.Open(new MgUserInformation(sessionId));
                resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService;
                featureService = conn.CreateService(MgServiceType.FeatureService) as MgFeatureService;
                map = new MgMap();
                map.Open(resourceService, mapName);
                layer = map.GetLayers().GetItem(layerId) as MgLayer;
                if (layer == null)
                {
                    throw new doSearchException("שכבה לא קיימת.");
                }

               /// string acFilter = 
               /// 
               /// checkProperty(Session[KeyACProperty].ToString(), Session[KeyACLayer].ToString()) ? String.Format("{0}='{1}'", Session[KeyACProperty].ToString(), txtSearch.Value) : String.Format("{0}={1}", Session[KeyACProperty].ToString(), txtSearch.Value);


                StringCollection FilterSelected = new StringCollection();
                foreach (ListItem item in txtSearch.Items)
                {
                   

                    if (item.Selected)
                    {
                        if (item.Text.Contains("'"))
                        {
                            if (!item.Text.Contains("\'"))
                            {
                                item.Text = item.Text.Replace("'", "\'");
                            }
                        
                        }

                        FilterSelected.Add(" NAME LIKE '" + item.Text + "' ");
                    }

                }
                int countselected = 0;
              string   acFilter = string.Empty;
                foreach (string item in FilterSelected)
                {
                    countselected++;

                    if (countselected == FilterSelected.Count)
                    {
                        acFilter += item;
                    }
                    else
                    {
                        acFilter += item + " OR ";
                    }

                }
                 
                 
                 
                 string mainSelection = GetMainFeatureSelection(Session[KeyACLayer].ToString(), acFilter);
                 litResultPanelTitle.Text = string.Empty;


                 //            MgLayer layer = (MgLayer) map.GetLayers().GetItem(Session[KeyACLayer].ToString()); 
              //   MgLayer layer = (MgLayer)map.GetLayers().GetItem("WFS_NWM_ALKFlurstueck_WFSExp");
             //     layerID = layer.GetFeatureSourceId(); 
                 MgResourceIdentifier featureResId = new MgResourceIdentifier(layer.GetFeatureSourceId());
                 //MgFeatureService featureService = (MgFeatureService) siteConnection.CreateService(MgServiceType.FeatureService); 

                 String className = layer.GetFeatureClassName();
                 String layerId2= layer.GetObjectId();
                 MgFeatureQueryOptions layerQuery = new MgFeatureQueryOptions();
                 layerQuery.SetFilter(acFilter);
                 MgFeatureReader featureReader = featureService.SelectFeatures(featureResId, className, layerQuery);

                 MgSelection selection = new MgSelection(map);

                 selection.AddFeatures(layer, featureReader, 0);

                 string selText = selection.ToXml();
                 // System.out.println(selText); 









                 //litResultPanelTitle.Text +=
                 // string zooom = String.Format("parent.parent.mapFrame.SetSelectionXML('{0}');parent.parent.mapFrame.ZoomSelection();", Server.HtmlEncode(mainSelection));
                 // System.Text.StringBuilder sb = new System.Text.StringBuilder();
                 // sb.Append("<script language='javascript'>function SelectMultiZoom() {");
                 // sb.Append(zooom);
                 //// sb.Append("alert('rrr')");
                 // // sb.Append("lbl.style.color='green';");
                 // sb.Append("}</script>");

                 // //Render the function definition. 
                 // //if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
                 // //{
                 //    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
                 // //}

                 // //Render the function invocation. 
                 // string funcCall = "<script language='javascript'>SelectMultiZoom();</script>";

                 // //if (!ClientScript.IsStartupScriptRegistered("JSScript"))
                 // //{
                 // ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
                 //}
                 //foreach (ListItem item in txtSearch.Items)
                 //{


                 //    if (item.Selected)
                 //    {
                 //        //litResultPanelTitle.Text +=
                 //        string zooom = String.Format("parent.parent.mapFrame.SetSelectionXML('{0}');parent.parent.mapFrame.ZoomSelection();", Server.HtmlEncode(mainSelection)); 
                 //        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                 //        sb.Append("<script language='javascript'>function SelectMultiZoom() {");
                 //        sb.Append(zooom);
                 //       // sb.Append("lbl.style.color='green';");
                 //        sb.Append("}</script>");

                 //        //Render the function definition. 
                 //        if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
                 //        {
                 //            ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
                 //        }

                 //        //Render the function invocation. 
                 //        string funcCall = "<script language='javascript'>SelectMultiZoom();</script>";

                 //        //if (!ClientScript.IsStartupScriptRegistered("JSScript"))
                 //        //{
                 //            ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
                 //        //}


                 //    }

                 MgFeatureQueryOptions opt = new MgFeatureQueryOptions();
                 opt.SetFilter(acFilter);
                 StringBuilder resultHtml = new StringBuilder();
                 //resultHtml.AppendLine("<table id='resultTable' class='sort' cellspacing='0' cellpadding='0' width='100%'>");
                 //resultHtml.AppendLine("<thead><tr style='display:none'>");

                 //foreach (var item in displayColumns)
                 //{
                 //    resultHtml.AppendFormat("<td>{0}</td>", item.Value);
                 //}

                 //resultHtml.AppendLine("</tr></thead>");

                 MgFeatureReader reader = featureService.SelectFeatures(
                                             new MgResourceIdentifier(layer.FeatureSourceId),
                                             layer.FeatureClassName,
                                             opt
                                          );
                 string[] keyFields = GetPrimaryKeyFieldName();


                 //string funcCall2 = string.Format("<script language='javascript'>CellClicked('{0}')</script>",GetSelectionXml(reader, keyFields));
                 string funcCall2 = string.Format("<script language='javascript'>CellClicked('{0}')</script>", selText);

                 //selText
                //MgFeatureQueryOptions opt = new MgFeatureQueryOptions();
                //opt.SetFilter(acFilter);
                //StringBuilder resultHtml = new StringBuilder();
             

                //MgFeatureReader reader = featureService.SelectFeatures(
                //                            new MgResourceIdentifier(layer.FeatureSourceId),
                //                            layer.FeatureClassName,
                //                            opt
                //                         );
                //string[] keyFields = GetPrimaryKeyFieldName();
               

                //string funcCall2 = string.Format("<script language='javascript'>CellClicked('{0}')</script>",GetSelectionXml(reader, keyFields));

                //if (!ClientScript.IsStartupScriptRegistered("JSScript"))
                //{
                ClientScript.RegisterStartupScript(this.GetType(), "JSScript2", funcCall2);
                //resultHtml.Append(GetValuesTable(reader, displayColumns));
                //resultHtml.AppendLine("</table>");
                ResultPanel.Visible = true;
                ResultContainer.Text = resultHtml.ToString();
            }
            catch (doSearchException ex)
            {
                _whithError = true;
                ShowError(ex.Message);
            }
            catch (MgException ex)
            {
                _whithError = true;
                if (__debugMode)
                    ShowError(ex.Message);
                else
                    ShowError("שגיאה, אנא וודא תקינות שאילתא.");
            }
               
              
                   
              
           

        }
            public  string[] GetAllCompletionList(string prefixText, int count, string contextKey)
        {
            string property = HttpContext.Current.Session[NullFiled].ToString();
            bool isString = true;
                //(bool)HttpContext.Current.Session[NullFiled];
            if (count == 0) count = 10;
            List<string> results = new List<string>();
            try
            {
                MgSiteConnection conn = new MgSiteConnection();
                conn.Open(new MgUserInformation(HttpContext.Current.Session[KeySession].ToString()));

                MgResourceService resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService;
                MgFeatureService featureService = conn.CreateService(MgServiceType.FeatureService) as MgFeatureService;

                MgMap map = new MgMap();
                map.Open(resourceService, HttpContext.Current.Session[KeyMapName].ToString());
                MgLayer layer = (MgLayer)map.GetLayers().GetItem(HttpContext.Current.Session[KeyACLayer].ToString());
                MgFeatureQueryOptions query = new MgFeatureQueryOptions();

                string filter = string.Empty;
                if (isString)
                    filter = "FeatId > 0 ";
                
               // string filter = "ID = 5 AND Y LIKE 'test*'";
                        //string.Format("FeatId > 0 LIKE '%{1}%'", HttpContext.Current.Session[NullFiled].ToString(), prefixText);
                query.SetFilter(filter);

                MgFeatureReader reader = featureService.SelectFeatures(new MgResourceIdentifier(layer.GetFeatureSourceId()), layer.GetFeatureClassName(), query);
                while (reader.ReadNext())
                {
                   // string val = GetPropertyValue(reader, property);
                     string val= reader.GetString("NAME");
                    results.Add(val);
                    //if (val.StartsWith(prefixText) && !results.Contains(val)) results.Add(val);
                    //if (results.Count >= count) break;
                }
                reader.Close();
                reader.Dispose();
            }
            catch (Exception e)
            {
                results.Add(e.Message);
            }
            results.OrderBy(k => k);
            return results.ToArray();
        }
        [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
        public static string[] GetCompletionList(string prefixText, int count, string contextKey)
        {
            string property = HttpContext.Current.Session[KeyACProperty].ToString();
            bool isString = (bool)HttpContext.Current.Session[KeyIsString];
            if (count == 0) count = 10;
            List<string> results = new List<string>();
            try
            {
                MgSiteConnection conn = new MgSiteConnection();
                conn.Open(new MgUserInformation(HttpContext.Current.Session[KeySession].ToString()));

                MgResourceService resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService;
                MgFeatureService featureService = conn.CreateService(MgServiceType.FeatureService) as MgFeatureService;

                MgMap map = new MgMap();
                map.Open(resourceService, HttpContext.Current.Session[KeyMapName].ToString());
                MgLayer layer = (MgLayer)map.GetLayers().GetItem(HttpContext.Current.Session[KeyACLayer].ToString());
                MgFeatureQueryOptions query = new MgFeatureQueryOptions();

                string filter = string.Empty;
                if (isString)
                    filter = string.Format("{0} LIKE '%{1}%'", HttpContext.Current.Session[KeyACProperty].ToString(), prefixText);
                query.SetFilter(filter);

                MgFeatureReader reader = featureService.SelectFeatures(new MgResourceIdentifier(layer.GetFeatureSourceId()), layer.GetFeatureClassName(), query);
                while (reader.ReadNext())
                {
                    string val = GetPropertyValue(reader, property);
                    if (val.StartsWith(prefixText) && !results.Contains(val)) results.Add(val);
                    if (results.Count >= count) break;
                }
                reader.Close();
                reader.Dispose();
            }
            catch (Exception e)
            {
                results.Add(e.Message);
            }
            results.OrderBy(k => k);
            return results.ToArray();
        }
        private static string GetPropertyValue(MgFeatureReader reader, string propertyName)
        {
            string val = string.Empty;

            if (reader.IsNull(propertyName)) return val;

            switch (reader.GetPropertyType(propertyName))
            {
                case MgPropertyType.Boolean:
                    val = reader.GetBoolean(propertyName).ToString();
                    break;
                case MgPropertyType.Byte:
                    val = reader.GetByte(propertyName).ToString();
                    break;
                case MgPropertyType.Single:
                    val = reader.GetSingle(propertyName).ToString();
                    break;
                case MgPropertyType.Double:
                    val = reader.GetDouble(propertyName).ToString();
                    break;
                case MgPropertyType.Int16:
                    val = reader.GetInt16(propertyName).ToString();
                    break;
                case MgPropertyType.Int32:
                    val = reader.GetInt32(propertyName).ToString();
                    break;
                case MgPropertyType.Int64:
                    val = reader.GetInt64(propertyName).ToString();
                    break;
                case MgPropertyType.String:
                    val = reader.GetString(propertyName);
                    break;
                case MgPropertyType.DateTime:
                    val = reader.GetDateTime(propertyName).ToString();
                    break;
                case MgPropertyType.Null:
                case MgPropertyType.Blob:
                case MgPropertyType.Clob:
                case MgPropertyType.Feature:
                case MgPropertyType.Geometry:
                case MgPropertyType.Raster:
                    break;
            }
            return val;
        }
        private static bool checkProperty(string property, string layerName)
        {
            try
            {
                MgSiteConnection conn = new MgSiteConnection();
                conn.Open(new MgUserInformation(HttpContext.Current.Session[KeySession].ToString()));

                MgResourceService resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService;
                MgFeatureService featureService = conn.CreateService(MgServiceType.FeatureService) as MgFeatureService;

                MgMap map = new MgMap();
                map.Open(resourceService, HttpContext.Current.Session[KeyMapName].ToString());
                MgLayer layer = (MgLayer)map.GetLayers().GetItem(layerName);
                MgFeatureQueryOptions query = new MgFeatureQueryOptions();
                query.AddFeatureProperty("NAME");
                query.SetFilter(String.Format("FeatId=1", property,"NAME"));
                MgFeatureReader reader = featureService.SelectFeatures(new MgResourceIdentifier(layer.GetFeatureSourceId()), layer.GetFeatureClassName(), query);
                reader.ReadNext();
                int propertyType = reader.GetPropertyType(property);
                return propertyType == MgPropertyType.String;
            }
            catch (Exception e) { }
            return false;
        }
        private static bool checkProperty(string property)
        {
            return checkProperty(property, HttpContext.Current.Session[KeyACLayer].ToString());
        }

        private string GetMainFeatureSelection(string layerName, string filter)
        {
            string result = String.Empty;

            if (String.IsNullOrEmpty(layerName) || String.IsNullOrEmpty(filter))
                return result;

            MgLayer mLayer = map.GetLayers().GetItem(layerName) as MgLayer;
            MgFeatureQueryOptions opt = new MgFeatureQueryOptions();
            opt.SetFilter(filter);

            MgFeatureReader reader = featureService.SelectFeatures(new MgResourceIdentifier(mLayer.FeatureSourceId), mLayer.FeatureClassName, opt);
            MgSelection sel = new MgSelection();
            sel.AddFeatures(mLayer, reader, 20);
            result = sel.ToXml();
            reader.Close();
            reader.Dispose();

            return result;
        }
    }
    [global::System.Serializable]
    public class doSearchException : Exception
    {
        public doSearchException() { }
        public doSearchException(string message) : base(message) { }
        public doSearchException(string message, Exception inner) : base(message, inner) { }
        protected doSearchException(
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context)
            : base(info, context) { }
    }
}